<?php
$pageTitle = "上传卡片";
$currentPage = "upload";
include('../resource/db/db.php');
include('../resource/navbar.php');

if (!isset($_COOKIE['user_id'])) {
    header("Location: ../main/login.php");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['title'])) {
    $user_id = $_COOKIE['user_id'];
    $title = $_POST['title'];
    $content = $_POST['content'];
    $set_id = $_POST['set_id'];

    $title = mysqli_real_escape_string($conn, $title);
    $content = mysqli_real_escape_string($conn, $content);
    $set_id = intval($set_id);

    // 获取最新的卡片 ID
    $sql = "SELECT card_id FROM cards ORDER BY card_id DESC LIMIT 1";
    $result = $conn->query($sql);
    $row = $result->fetch_assoc();
    if (!$row) {
        $card_id = 1;
    } else {
        $card_id = $row['card_id'] + 1;
    }

    // 处理正面图片上传
    if (isset($_FILES['images1'])) {
        $imageDir = '../uploads/';
        $imagePaths = [];
        foreach ($_FILES['images1']['tmp_name'] as $index => $tmpName) {
            if ($_FILES['images1']['error'][$index] === UPLOAD_ERR_OK) {
                // 保存以star为根目录的路径
                $imagePath = $imageDir . $_FILES['images1']['name'][$index];
                if (move_uploaded_file($tmpName, $imagePath)) {
                    $imagePaths[] = $imagePath;
                }
            }
        }
        foreach ($imagePaths as $imagePath) {
            // 固定图片宽高不超过
            $title .= '<img src="' . $imagePath . '" style="max-width: 1000px; max-height: 100px;">';
        }
    }

    // 处理反面图片上传
    if (isset($_FILES['images2'])) {
        $imageDir = '../uploads/';
        $imagePaths = [];
        foreach ($_FILES['images2']['tmp_name'] as $index => $tmpName) {
            if ($_FILES['images2']['error'][$index] === UPLOAD_ERR_OK) {
                // 保存以star为根目录的路径
                $imagePath = $imageDir . $_FILES['images2']['name'][$index];
                if (move_uploaded_file($tmpName, $imagePath)) {
                    $imagePaths[] = $imagePath;
                }
            }
        }
        foreach ($imagePaths as $imagePath) {
            // 固定图片宽高不超过
            $content .= '<img src="' . $imagePath . '" style="max-width: 1000px; max-height: 100px;">';
        }
    }

    // 创建卡片
    $sql = "INSERT INTO cards (user_id, title, content, set_id, card_id) 
    VALUES ('$user_id', '$title', '$content', '$set_id', '$card_id')";

    if ($conn->query($sql) === TRUE) {
        // 创建学习记录并将下次复习时间设置为当天
        $sql_record = "INSERT INTO study_records (card_id, set_id, user_id, next_review) 
        VALUES ('$card_id', '$set_id', '$user_id', NOW())";
        if ($conn->query($sql_record) === TRUE) {
            echo "上传成功！";
            // 刷新
            header("Location: upload.php");
            exit();
        } else {
            echo "Error: " . $sql_record . "<br>" . $conn->error;
        }
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}

// 获取用户的卡组及其卡片数量和创建时间
$user_id = $_COOKIE['user_id'];
$sets_sql = "SELECT s.set_id, s.name, s.created_at, COUNT(c.card_id) AS card_count 
             FROM sets s
             LEFT JOIN cards c ON s.set_id = c.set_id
             WHERE s.user_id='$user_id' AND s.is_deleted=FALSE
             GROUP BY s.set_id";
$sets_result = $conn->query($sets_sql);
?>

<!DOCTYPE html>
<html>

<head>
    <title>上传卡片</title>
    <link rel="stylesheet" href="../resource/css/styles.css">
</head>

<body>
    <div class="container">
        <div style="display: flex; flex-direction:row;">
            <h2>上传卡片</h2>
            <button type="button" class="btn btn-secondary" onclick="window.location.href='batch-upload.php'" style="margin-left: 80%;">批量创建</button>
        </div>
        <div class="upload-card">
            <form method="post" action="" enctype="multipart/form-data">
                <div class="form-group title">
                    <label for="title">正面（标题）:</label>
                    <textarea id="title" name="title" class="form-control" required></textarea>
                    <label for="images">正面图片:</label>
                    <input type="file" id="images1" name="images1[]" class="form-control" accept="image/*" multiple>
                </div>
                <div class="form-group content">
                    <label for="content">反面（内容）:</label>
                    <textarea id="content" name="content" class="form-control" required></textarea>
                    <label for="images">反面图片:</label>
                    <input type="file" id="images2" name="images2[]" class="form-control" accept="image/*" multiple>
                </div>
                <div class="form-group">
                    <label for="set_id">选择卡组:</label>
                    <select id="set_id" name="set_id" class="form-control" required>
                        <?php
                        if ($sets_result->num_rows > 0) {
                            while ($row = $sets_result->fetch_assoc()) {
                                echo "<option value='" . $row['set_id'] . "'>" . $row['name'] . " - " . $row['card_count'] . " 张卡片 - 创建时间: " . $row['created_at'] . "</option>";
                            }
                        } else {
                            echo "<option value='' disabled>暂无卡组</option>";
                        }
                        ?>
                    </select>
                </div>
                <div class="btn">
                    <button type="submit" class="btn btn-primary">确认</button>
                </div>
            </form>
        </div>
    </div>
    <div class="container">
        <h2>新建卡组</h2>
        <div class="upload-set">
            <div class="form-group">
                <label for="new_set">卡组名称:</label>
                <input type="text" id="new_set" name="new_set" class="form-control">
                <label for="new_set_info">卡组简介:</label>
                <input type="text" id="new_set_info" name="new_set_info" class="form-control">
                <div class="btn">
                    <button type="button" id="create_set" class="btn btn-primary">确认</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.getElementById('create_set').addEventListener('click', function() {
            const newSetName = document.getElementById('new_set').value;
            const newSetInfo = document.getElementById('new_set_info').value;
            const userId = parseInt("<?php echo $_COOKIE['user_id']; ?>");
            if (newSetName) {
                const xhr = new XMLHttpRequest();
                xhr.open("POST", "create-set.php", true);
                xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        const response = xhr.responseText;
                        if (response === "已经有相同名称的卡组") {
                            alert("已经有相同名称的卡组");
                        } else {
                            const select = document.getElementById('set_id');
                            const option = document.createElement('option');
                            option.value = response;
                            option.text = newSetName;
                            select.appendChild(option);
                            alert("新建卡组成功");
                        }
                    }
                };
                xhr.send("user_id=" + userId + "&name=" + encodeURIComponent(newSetName) + "&info=" + encodeURIComponent(newSetInfo));
            } else {
                alert("请输入卡组名称。");
            }
        });
    </script>
</body>

</html>